package com.stt.videoprocess.design.service;

import com.stt.videoprocess.design.model.VideoTask;
import com.stt.videoprocess.design.processor.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 视频处理服务实现
 * 1. 创建处理任务
 * 2. 执行处理流程
 * 3. 状态维护和指标收集
 */
@Service
@Slf4j
public class DesignVideoProcessingService {
    private final ConcurrentHashMap<String, VideoTask> taskStore = new ConcurrentHashMap<>();

    /**
     * 创建视频处理任务
     * @param file 上传的视频文件
     * @return 任务ID
     */
    public String createProcessingTask(MultipartFile file) {
        String taskId = UUID.randomUUID().toString();
        VideoTask task = new VideoTask();
        task.setTaskId(taskId);
        task.setOriginalFile(file.getOriginalFilename());
        taskStore.put(taskId, task);

        // 启动异步处理
        new Thread(() -> processVideo(task)).start();
        log.info("创建新的处理任务: {}", taskId);
        return taskId;
    }

    /**
     * 执行视频处理流程
     */
    private void processVideo(VideoTask task) {
        try {
            // 修改任务状态为处理中
            task.changeState(task.getState().startProcessing(task));

            // 构建组合处理管道（装饰器模式+组合模式）
            try {
                // 创建串行处理管道
                SerialProcessor pipeline = new SerialProcessor();
                // 添加处理步骤
                pipeline.addProcessor(new WatermarkProcessor(new BaseProcessor()));
                pipeline.addProcessor(new FilterProcessor(new BaseProcessor(), "Cinematic"));
                pipeline.addProcessor(new MuteProcessor(new BaseProcessor()));

                // 执行处理管道
                pipeline.process(task);
            } catch (Exception e) {
                throw new RuntimeException("任务处理失败", e);
            }

            // 所有处理步骤完成后更新状态
            task.changeState(task.getState().completeProcessing(task));
        } catch (Exception e) {
            log.error("任务处理失败，编号为: " + task.getTaskId(), e);
            task.changeState(task.getState().failProcessing(task, e.getMessage()));
            rollbackOperations(task.getTaskId());
        }
    }

    /**
     * 获取任务状态
     */
    public VideoTask getTaskStatus(String taskId) {
        return taskStore.get(taskId);
    }

    /**
     * 操作回滚实现
     */
    private void rollbackOperations(String taskId) {
        log.warn("任务开始回滚: {}", taskId);
        // 根据实际需要实现回滚逻辑
    }
}
